package com.czh.springboot04.service.serviceimpl;

import com.czh.springboot04.entity.Question;
import com.czh.springboot04.entity.Reply;
import com.czh.springboot04.entity.User;
import com.czh.springboot04.mapper.QuestionMapper;
import com.czh.springboot04.mapper.ReplyMapper;
import com.czh.springboot04.mapper.UserMapper;
import com.czh.springboot04.service.ReplyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {
    @Autowired
    private ReplyMapper replyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public int addReply(Reply reply) {
        int j = questionMapper.addQuestion(reply.getQuestion());
        int k = replyMapper.addReply(reply);
        if (j > 0&&k>0) {
            return k;
        }
        return 0;
    }

    @Override
    public int deleteReply(int id) {
        Reply reply = replyMapper.findById(id);
        if (reply == null) {
            return 0;
        }
        int i = userMapper.deleteUser(reply.getUserId());
        int j = questionMapper.deleteQuestion(reply.getQuestionId());
        int k = replyMapper.deleteReply(id);
        if (i > 0 && j > 0&&k>0) {
            return k;
        }
        return 0;
    }

    @Override
    public int updateReply(Reply reply) {
        int i = userMapper.updateU(reply.getUser());
        int j = questionMapper.updateQuestion(reply.getQuestion());
        int k = replyMapper.updateReply(reply);
        if (i > 0 && j > 0&&k>0) {
            return k;
        }
        return 0;
    }

    @Override
    public PageInfo<Reply> findAll(int pageNum, int pageSize, Reply reply) {
        PageHelper.startPage(pageNum,pageSize);
        List<Reply> replies=replyMapper.findAll(reply);
        return new PageInfo<>(replies);
    }
    @Override
    public List<Reply> findByQid(int qusetionId) {
        List<Reply> replies=replyMapper.findByQid(qusetionId);
        for(Reply reply:replies){
           Question question = questionMapper.findById(reply.getQuestionId());
           reply.setQuestionId(question.getId());

        }
//        PageInfo<Reply> pageInfo=new PageInfo<>(replies);
        return replies;
    }
    @Override
    public List<Reply> findById(int id) {
        List<Reply> replies = replyMapper.findByQid(id);
        for(Reply reply:replies){
            //System.out.println(reply.getFid());
            Question question = questionMapper.findById(reply.getFid());
            reply.setQuestion(question);
            //System.out.println(reply.getUserId());
            User user=userMapper.selectById(reply.getUserId());
            reply.setUser(user);
        }

        return replies;
    }
}
